import React, { useState } from 'react';
import { Typography, Table, Card, Space, Button, Tag, Progress, Descriptions, Modal, Form, Select, Input } from 'antd';
import {
  ClusterOutlined,
  PlusOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  DeleteOutlined,
  MonitorOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;

interface K8SCluster {
  id: string;
  name: string;
  status: 'running' | 'stopped' | 'creating' | 'error';
  version: string;
  nodeCount: number;
  cpuUsage: number;
  memoryUsage: number;
  provider: string;
  region: string;
  created: string;
}

interface Node {
  id: string;
  name: string;
  status: 'ready' | 'not_ready' | 'unknown';
  role: 'master' | 'worker';
  cpu: string;
  memory: string;
  pods: number;
}

const ClusterManage: React.FC = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedCluster, setSelectedCluster] = useState<K8SCluster | null>(null);
  const [form] = Form.useForm();

  // 模拟集群数据
  const [clusters] = useState<K8SCluster[]>([
    {
      id: '1',
      name: 'production-cluster',
      status: 'running',
      version: 'v1.28.2',
      nodeCount: 5,
      cpuUsage: 65,
      memoryUsage: 72,
      provider: '阿里云',
      region: '华东1',
      created: '2024-01-10'
    },
    {
      id: '2',
      name: 'development-cluster',
      status: 'running',
      version: 'v1.27.8',
      nodeCount: 3,
      cpuUsage: 45,
      memoryUsage: 38,
      provider: '腾讯云',
      region: '华南1',
      created: '2024-01-12'
    },
    {
      id: '3',
      name: 'test-cluster',
      status: 'stopped',
      version: 'v1.28.0',
      nodeCount: 2,
      cpuUsage: 0,
      memoryUsage: 0,
      provider: 'AWS',
      region: 'us-east-1',
      created: '2024-01-08'
    }
  ]);

  // 模拟节点数据
  const [nodes] = useState<Node[]>([
    { id: '1', name: 'master-1', status: 'ready', role: 'master', cpu: '2 cores', memory: '4GB', pods: 15 },
    { id: '2', name: 'worker-1', status: 'ready', role: 'worker', cpu: '4 cores', memory: '8GB', pods: 25 },
    { id: '3', name: 'worker-2', status: 'ready', role: 'worker', cpu: '4 cores', memory: '8GB', pods: 22 },
    { id: '4', name: 'worker-3', status: 'not_ready', role: 'worker', cpu: '4 cores', memory: '8GB', pods: 0 },
  ]);

  const getStatusConfig = (status: K8SCluster['status']) => {
    const configs = {
      running: { color: 'success', text: '运行中' },
      stopped: { color: 'default', text: '已停止' },
      creating: { color: 'processing', text: '创建中' },
      error: { color: 'error', text: '异常' }
    };
    return configs[status];
  };

  const getNodeStatusConfig = (status: Node['status']) => {
    const configs = {
      ready: { color: 'success', text: '就绪' },
      not_ready: { color: 'error', text: '未就绪' },
      unknown: { color: 'default', text: '未知' }
    };
    return configs[status];
  };

  const handleViewDetail = (cluster: K8SCluster) => {
    setSelectedCluster(cluster);
    setDetailModalVisible(true);
  };

  const handleCreateCluster = async () => {
    try {
      const values = await form.validateFields();
      console.log('创建集群:', values);
      setModalVisible(false);
      form.resetFields();
      // 实现创建逻辑
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleStatusChange = (cluster: K8SCluster, action: 'start' | 'stop') => {
    console.log(`${action} 集群:`, cluster.name);
    // 实现状态更改逻辑
  };

  const clusterColumns: ColumnsType<K8SCluster> = [
    {
      title: '集群信息',
      key: 'clusterInfo',
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Space>
            <ClusterOutlined style={{ color: '#1890ff' }} />
            <Text strong>{record.name}</Text>
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.provider} · {record.region}
          </Text>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: K8SCluster['status']) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'K8S版本',
      dataIndex: 'version',
      key: 'version',
      render: (version: string) => <Tag color="blue">{version}</Tag>,
    },
    {
      title: '节点数',
      dataIndex: 'nodeCount',
      key: 'nodeCount',
      render: (count: number) => <Text>{count}</Text>,
    },
    {
      title: '资源使用率',
      key: 'usage',
      render: (_, record) => (
        <Space direction="vertical" size="small" style={{ minWidth: 120 }}>
          <div>
            <Text style={{ fontSize: 12 }}>CPU: {record.cpuUsage}%</Text>
            <Progress 
              percent={record.cpuUsage} 
              size="small" 
              status={record.cpuUsage > 80 ? 'exception' : 'normal'}
              showInfo={false}
            />
          </div>
          <div>
            <Text style={{ fontSize: 12 }}>内存: {record.memoryUsage}%</Text>
            <Progress 
              percent={record.memoryUsage} 
              size="small" 
              status={record.memoryUsage > 80 ? 'exception' : 'normal'}
              showInfo={false}
            />
          </div>
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      key: 'created',
      sorter: (a, b) => new Date(a.created).getTime() - new Date(b.created).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            size="small"
            icon={<MonitorOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          
          {record.status === 'running' ? (
            <Button
              type="link"
              size="small"
              icon={<PauseCircleOutlined />}
              onClick={() => handleStatusChange(record, 'stop')}
            >
              停止
            </Button>
          ) : (
            <Button
              type="link"
              size="small"
              icon={<PlayCircleOutlined />}
              onClick={() => handleStatusChange(record, 'start')}
              disabled={record.status === 'creating'}
            >
              启动
            </Button>
          )}
          
          <Button
            type="link"
            size="small"
            icon={<SettingOutlined />}
          >
            配置
          </Button>
          
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            disabled={record.status === 'running'}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const nodeColumns: ColumnsType<Node> = [
    {
      title: '节点名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record) => (
        <Space>
          <Text strong>{text}</Text>
          <Tag color={record.role === 'master' ? 'gold' : 'blue'}>
            {record.role === 'master' ? '主节点' : '工作节点'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Node['status']) => {
        const config = getNodeStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'CPU',
      dataIndex: 'cpu',
      key: 'cpu',
    },
    {
      title: '内存',
      dataIndex: 'memory',
      key: 'memory',
    },
    {
      title: 'Pods数量',
      dataIndex: 'pods',
      key: 'pods',
      render: (pods: number) => <Text>{pods}</Text>,
    },
  ];

  // 统计信息
  const stats = {
    total: clusters.length,
    running: clusters.filter(c => c.status === 'running').length,
    totalNodes: clusters.reduce((sum, cluster) => sum + cluster.nodeCount, 0),
    avgCpuUsage: Math.round(clusters.reduce((sum, cluster) => sum + cluster.cpuUsage, 0) / clusters.length),
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'flex-start',
        marginBottom: '24px'
      }}>
        <div>
          <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
            <ClusterOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            K8S集群管理
          </Title>
          <Text type="secondary">管理Kubernetes集群和容器编排服务</Text>
        </div>
        <Button 
          type="primary" 
          size="large"
          icon={<PlusOutlined />}
          onClick={() => setModalVisible(true)}
        >
          创建集群
        </Button>
      </div>

      {/* 统计卡片 */}
      <div style={{ 
        display: 'grid', 
        gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
        gap: '16px', 
        marginBottom: '24px' 
      }}>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>{stats.total}</div>
            <div style={{ color: '#666' }}>总集群数</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{stats.running}</div>
            <div style={{ color: '#666' }}>运行中</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>{stats.totalNodes}</div>
            <div style={{ color: '#666' }}>总节点数</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>{stats.avgCpuUsage}%</div>
            <div style={{ color: '#666' }}>平均CPU使用率</div>
          </div>
        </Card>
      </div>

      {/* 集群列表 */}
      <Card>
        <Table
          columns={clusterColumns}
          dataSource={clusters}
          rowKey="id"
          pagination={{
            total: clusters.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 创建集群模态框 */}
      <Modal
        title="创建K8S集群"
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        onOk={handleCreateCluster}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            provider: 'aliyun',
            version: 'v1.28.2',
            nodeCount: 3
          }}
        >
          <Form.Item
            name="name"
            label="集群名称"
            rules={[{ required: true, message: '请输入集群名称' }]}
          >
            <Input placeholder="例如：production-cluster" />
          </Form.Item>
          
          <Form.Item
            name="provider"
            label="云服务商"
            rules={[{ required: true, message: '请选择云服务商' }]}
          >
            <Select>
              <Option value="aliyun">阿里云</Option>
              <Option value="tencent">腾讯云</Option>
              <Option value="aws">AWS</Option>
              <Option value="azure">Azure</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="region"
            label="地域"
            rules={[{ required: true, message: '请选择地域' }]}
          >
            <Select>
              <Option value="cn-hangzhou">华东1(杭州)</Option>
              <Option value="cn-shanghai">华东2(上海)</Option>
              <Option value="cn-beijing">华北2(北京)</Option>
              <Option value="cn-shenzhen">华南1(深圳)</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="version"
            label="K8S版本"
            rules={[{ required: true, message: '请选择K8S版本' }]}
          >
            <Select>
              <Option value="v1.28.2">v1.28.2 (推荐)</Option>
              <Option value="v1.27.8">v1.27.8</Option>
              <Option value="v1.26.12">v1.26.12</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="nodeCount"
            label="工作节点数量"
            rules={[{ required: true, message: '请输入节点数量' }]}
          >
            <Select>
              <Option value={1}>1个节点</Option>
              <Option value={3}>3个节点</Option>
              <Option value={5}>5个节点</Option>
              <Option value={10}>10个节点</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 集群详情模态框 */}
      <Modal
        title={`集群详情 - ${selectedCluster?.name}`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedCluster && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: '24px' }}>
              <Descriptions.Item label="集群名称" span={2}>
                {selectedCluster.name}
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getStatusConfig(selectedCluster.status).color}>
                  {getStatusConfig(selectedCluster.status).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="K8S版本">
                {selectedCluster.version}
              </Descriptions.Item>
              <Descriptions.Item label="云服务商">
                {selectedCluster.provider}
              </Descriptions.Item>
              <Descriptions.Item label="地域">
                {selectedCluster.region}
              </Descriptions.Item>
              <Descriptions.Item label="节点数量">
                {selectedCluster.nodeCount}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {selectedCluster.created}
              </Descriptions.Item>
            </Descriptions>

            <Title level={5}>节点信息</Title>
            <Table
              columns={nodeColumns}
              dataSource={nodes}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ClusterManage; 